<?php
namespace app\api\controller;
use app\admin\model\Article;
use app\admin\model\SystemConfig;
use app\api\service\UserService;
use app\common\controller\Api;
use app\common\model\BalanceConfig;
use app\common\model\CardConfig;
use app\common\model\contact\Support;
use app\common\model\Feedback;
use app\common\model\Lights;
use app\common\model\MoneyLog;
use app\common\model\monthly\card\Payments;
use app\common\model\Upgraderules;
use DateTime;
use fast\Http;
use think\Db;

class Wechat extends Api
{
    protected $noNeedLogin = ['code', 'login','getWxcode'];
    protected $noNeedRight = ['*'];
    protected $appid;
    protected $secret;
    protected $loginUrl;

    public function __construct()
    {
        $this->appid = get_addon_config("loginmobile")['appId'];
        $this->secret = get_addon_config("loginmobile")['secretId'];
        $this->loginUrl = get_addon_config("loginmobile")['loginUrl'];
        parent::__construct();
    }

    //https://hongqi-b.maoln.com/api/Auth_login_with_wechat/test

    /**
     * 登录第一步，获取openid 跟 session_key
     */
    public function code()
    {
        $code = $this->request->param('code');
        if (!$code) {
            $this->error('code不能为空');
        }
        self::getOpenid($code);
    }


    /**
     * @param $code 用来交换获取openid 跟 session_key
     */
    public function getOpenid($code)
    {
        $url = sprintf($this->loginUrl, $this->appid, $this->secret, $code);
        $result = Http::get($url);
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            $this->error('获取sessin_key及openID时异常');
        }
        if (isset($wxResult['errcode']) && $wxResult['errcode'] != 0) {
            $this->error($wxResult['errmsg']);
        }
        $item = [
            'openid' => $wxResult['openid'],
            'session_key' => $wxResult['session_key']
        ];
        return $item;
    }


    /**
     * 用户登录
     */
    public function login()
    {
        $encryptedData = $this->request->post('encryptedData');
        $code = $this->request->post('code');
        $iv = $this->request->post('iv');
        $code_info = $this->getOpenid($code);
        $openid = $code_info['openid'];

        $userinfo = \app\admin\model\User::where(['openid' => $openid])->find();
        if ($userinfo) {
            if($userinfo['status']!='normal'){
                $this->error('该账户已停用');
            }
            $this->auth->direct($userinfo['id']);
        } else {
            $user = new \app\admin\model\User();
            $user->data([
                'openid' => $openid,
                'status' => 'normal',
                'jointime' =>time(),
                'avatar'=>'https://zhuoyaoji.com.cn/uploads/20250227/264dda9c8d8e235c9bc08d3ca8a0e0dc.png'
            ]);
            $user->save();
            $this->auth->direct($user->id);
        }

        $phone_user = \app\admin\model\User::get($this->auth->id);
        //获取手机号
        $errCode = self::decryptData($encryptedData, $iv, $data, $code_info['session_key'], $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {

                if($phone_user['mobile']==""||$phone_user['mobile']==null){
//                    $mobile= \app\admin\model\User::where('mobile','=',$result['phoneNumber'])->find();
//                    if($mobile){
//                        $this->error('该手机号已存在');
//                    }
                }
                $add['mobile']=$result['phoneNumber'];
                \app\admin\model\User::where('id','=',$phone_user['id'])->update($add);

            } else {
                $this->error('号码获取失败');
            }
        }
        $token = $user['token'] = $this->auth->getToken();
        $this->success('登录成功', ['token' => $token, 'user' => $this->auth->getUserinfo()]);

    }

    public function  user_info(){
        $user= \app\common\model\User::where('id',$this->auth->id)->field('id,nickname,avatar,gender,money,score,mobile,link_img,month_card,month_card_time,level_id')->find();
        if($user['month_card_time']==null){
            $user['month_card_time']='无';
        }
        if($user['level_id']==0){
            $level_name='普通会员';
        }else{
            $level_name=  Upgraderules::where('id',$user['level_id'])->value('level_name');
        }
        $user['level_name']=$level_name;
        $this->success('获取成功', $user);
    }



    /*
     * 修改个人信息
     */

    public function save()
    {

        // 检查并获取头像
        if ($avatar = input('avatar')) {
            $data['avatar'] = $avatar;
        }
        // 检查并获取昵称
        if ($nickname = input('nickname')) {
            $data['nickname'] = $nickname;
        }
        if ($mobile = input('mobile')) {
            $data['mobile'] = $mobile;
        }
        $gender=    input('gender');
        if($gender!=null){
            $data['gender'] = $gender;
        }
        if ($link_img = input('link_img')) {
            $data['link_img'] = $link_img;
        }
        if (empty($data)) {
            $this->error('没有要更新的内容');

        }
//        $user = $this->auth->getUser();
        $result=\app\common\model\User::where('id','=',$this->auth->id)->update($data);
        if ($result) {
            $this->success('修改成功');

        }
        $this->error('修改失败');
    }

    /*
     * 联系客服
     */
    public function contact_support(){

        if (!$message= input('message')) {
            $this->error(__('请输入留言内容'));
        }
        if (!$contact_number= input('contact_number')) {
            $this->error(__('请输入联系电话'));
        }
        if (!$name= input('name')) {
            $this->error(__('请联系联系人'));
        }
        $result = Support::create([
            'user_id' => $this->auth->id,
            'message' =>$message,
            'contact_number' => $contact_number,
            'name'=>$name,
        ]);
        $this->success('提交成功', []);
    }

     /*
     * 意见反馈
     */
    public function feedback(){

        if (!$content= input('content')) {
            $this->error(__('请输入反馈内容'));
        }
        $image= input('image');
        $result = Feedback::create([
            'user_id' => $this->auth->id,
            'image' =>$image,
            'content' => $content,

        ]);
        $this->success('提交成功', []);
    }
    /*
     * 关于我们
     */
    public function about(){

        $sys=Article::where('type','about')->field('content,video_url,carousel')->find();
        $sys['video_url']= $sys['video_url']==""?[]:explode(',', $sys['video_url']);
        $imagesArray = explode(',', $sys['carousel']);
        $resultArray = [];
        foreach ($imagesArray as $url) {
            $resultArray[] = ['image' => trim($url)]; // 使用 trim 去除多余的空格
        }
        $sys['carousel'] = $resultArray;
        $this->success('提交成功', $sys);
    }


    /*
     * 余额日志
     */

    public function money_log(){
        $list= MoneyLog::where('user_id','=',$this->auth->id)->order('id desc')->paginate(10);
        foreach ($list as $row) {
            $row['createtime_text'] = date('Y-m-d H:i:s', $row['createtime']);
            $row['op']=$row['before']>$row['after']?'':'+';
        }
        if ($list) {
            DB::commit();
            $this->success('操作成功', $list);
        }else{
            $this->error('余额失败');
        }
    }

    /*
     * 余额充值列表
     */
    public function balance_recharge_list(){
        $list=BalanceConfig::where('status',1)->field('id,recharge_amount,bonus_amount')->order('weigh desc')->select();
        $this->success('操作成功', $list);
    }

    /*
     * 客服电话
     */

    public function customer_phone(){
        $SystemConfig=SystemConfig::field('hotline')->find();
        $this->success('操作成功', $SystemConfig);

    }

    /*
     * 余额充值
     */
    public function balance_recharge(){
        if (!$id= input('id')) {
            $this->error(__('请选择'));
        }
        $Balance = BalanceConfig::where('id', $id)->find();
        $result = \app\common\model\recharge\Payments::create(
            [
                'user_id' => $this->auth->id,
                'recharge_amount' => $Balance['recharge_amount'],
                'bonus_amount' => $Balance['bonus_amount'],
                'order_no' => order_no(),
            ]);
        $service=new UserService();
        $payment=$service->recharge_payment($result->id,$result->user_id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }

     /*
     * 月卡充值列表
     */
    public function card_recharge_list(){
        $list=CardConfig::where('status',1)->field('id,months,price,usage_count')->order('weigh desc')->select();
        $this->success('操作成功', $list);
    }
    /*
     * 月卡充值
     */
    public function card_recharge(){
        if (!$id= input('id')) {
            $this->error(__('请选择'));
        }
        $CardConfig = CardConfig::where('id', $id)->find();
        $result = \app\common\model\monthly\card\Payments::create(
            [
                'user_id' => $this->auth->id,
                'amount' => $CardConfig['price'],
                'months' => $CardConfig['months'],
                'usage_count' => $CardConfig['usage_count'],
                'order_no' => order_no(),
            ]);
        $service=new UserService();
        $payment=$service->car_payment($result->id,$result->user_id);
        $this->success('请求成功', [
            'payment' => $payment,
        ]);
    }



    /**
     * 获取手机号
     */
    public function getPhone($iv,$encryptedData,$code)
    {
        $datainfo = $this->auth->getUserinfo();
        $user = \app\admin\model\User::get($datainfo['id']);

        $code_info = $this->getOpenid($code);
        $errCode = self::decryptData($encryptedData, $iv, $data, $code_info['session_key'], $this->appid);
        if ($errCode == 0) {
            $result = json_decode($data, true);
            if (isset($result['phoneNumber'])) {
                $this->success('获取成功', $result);
            } else {
                $this->error('号码获取失败');
            }
        } else {
            $this->error('用户信息更新失败');
        }
    }


    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, &$data, $sessionKey, $appid)
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41003;
        }
        $data = $result;
        return 0;
    }

    public function getWxAccessToken() {

        $appid =  $this->appid;
        $appsecret = $this->secret;

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
        $access_token = makeRequest($url);
        $access_token = json_decode($access_token['result'], true);

        return $access_token;
    }




}